<template>
  <scroll 
    class="suggest" 
    :data='result' 
    ref='suggest'
    @scrollToEnd='scrollToEnd' 
    :pullup='pullup'
    @beforeScroll='listScroll'
    :beforeScroll='beforeScroll'
   >
    <ul class="suggest-list">
      <li 
        class="suggest-item" 
        v-for="(item,index) of result" :key="index"
        @click.prevent="selectItem(item)"
      >
        <div class="icon">
          <i :class="getIconClas(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <loading v-show="hasMore" title=""></loading>
     </ul>
     <div class="no-result-wrapper" v-show="!result.length && !hasMore">
       <no-result title="抱歉！没有搜到您想要的结果"></no-result>
     </div>
  </scroll>
</template>

<script>
import {search} from 'api/search'
import {ERR_OK} from 'api/config'
import {createSong} from 'common/js/song'
import Scroll from 'base/scroll/scroll'
import Loading from 'base/loading/loading'
import Singer from 'common/js/singer'
import { mapMutations, mapActions } from 'vuex'
import NoResult from 'base/no-result/no-result'

const TYPE_SINGER='singer'
const perpage=20

export default {
  components: {
    Scroll,
    Loading,
    NoResult
  },
  props: {
    query:{
      type: String,
      default: ''
    },
    showSinger: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      page: 1,    //当前页面
      result: [], //搜索的数据
      pullup: true, //scroll 下滑选项
      hasMore: true, //是否还有数据
      beforeScroll: true //监听滚动
    }
  },
  methods: {
    // 搜数据
    search() {
      this.hasMore=true
      this.page=1  //当前页面设置为1
      // query改变时 滚动到第一条搜索数据位置
      this.$refs.suggest.scrollTo(0,0)

      search(this.query,this.page,this.showSinger,perpage).then(res=> {
        if(res.code===ERR_OK) {
          // 处理数据
          this.result= this._getResult(res.data)
          // 检查是否还有数据
          this.checkMore(res.data)
        }
      })
    },

    //滚到底部 下拉加载
    scrollToEnd(){
      // 没有数据 退出
      if(!this.hasMore) {
        return
      }
      this.page++
      search(this.query,this.page,this.showSinger,perpage).then(res => {
        if(res.code===ERR_OK) {
          //result 合并 第二页的数据
          this.result= this.result.concat(this._getResult(res.data).slice(1,res.data.length))
          this.checkMore(res.data)
        }
      })
    },
    //列表滚动，输入框失去焦点（隐藏键盘）
    listScroll() {
      this.$emit('listScroll')
    },

    //检查是否还有数据
    checkMore(list) {
      const song=list.song
      if(!song.list.length ||(song.curnum+song.curpage*perpage) > song.totalnum ){
        this.hasMore=false
      }
    }, 
    _getResult(data) {
      let ret = []
      if(data.zhida && data.zhida.singerid) {
        //使用es6对象扩展运算符...把两个对象添加到一个对象上
        ret.push({...data.zhida, ...{type: TYPE_SINGER}})
      }
      if(data.song){
        ret = ret.concat(this._normalList(data.song.list))//合并时出现难题
      }
      return ret
    },
    _normalList(list) {
      let ret= []
      list.forEach(musicData => {
        if(musicData.songid && musicData.albumid) {
          ret.push(createSong(musicData))
        }
      });
      return ret
    },

    //动态添加 icon样式
    getIconClas(item) {
      //歌手
      if(item.type===TYPE_SINGER){
        return 'icon-mine'
      }else {
        return 'icon-music'
      }
    },
    getDisplayName(item) {
      if(item.type===TYPE_SINGER){
        return item.singername
      }else {
        return `${item.name}-${(item.singer)}`
      }
    },

    //点击搜索的 item
    selectItem(item){
      // 点击的是歌手 
      if(item.type===TYPE_SINGER){
        let singer=new Singer({
          id: item.singermid,
          name: item.singername
        })
        // 跳转至singer-detail页面  
        this.$router.push({
          // router里注册search的children页面
          path: `/search/${singer.id}`
        })
        //修改mutations
        this.setSinger(singer)
      } else {
        // 点击的是歌曲 插入歌曲到播放列表 提交actions
        this.insertSong(item)
      }
      this.$emit('select')
    },
    ...mapMutations({
      setSinger:'SET_SINGER'
    }),
    ...mapActions([
      'insertSong'
    ])
  },
  watch: {
    // 每次query改变都调用search查找新数据
    query() {
      this.search()
    }
  },
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>